package tw.spring.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tw.spring.demo.model.Article;

/**
 * @author: 陈艺博
 * @date: 2021-02-04 20:35
 * @description: 测试Controller
 **/
@Slf4j
@RestController
public class DemoController {

    /**
     * 返回XML格式的数据
     */
    @GetMapping(value = "demo", produces = MediaType.APPLICATION_XML_VALUE)
    public String demo() {
        return xml;
    }

    String xml = "<articles>\n" +
            "    <article>\n" +
            "        <author>YiBo</author>\n" +
            "        <title>制作一个XMl</title>\n" +
            "        <content>这是一个自定义的XML文件格式</content>\n" +
            "    </article>\n" +
            "</articles>";

    @PostMapping(value = "json")
    public String obj2Json(@RequestBody String jsonStr) throws JsonProcessingException {
        log.info(jsonStr);
        //jackson的ObjectMapper 转换对象
        ObjectMapper mapper = new ObjectMapper();
        //将jsonStr转换为Ademo类的对象
        Article article = mapper.readValue(jsonStr, Article.class);
        log.debug("article: "+article);
        //将某个java对象转换为JSON字符串
        return mapper.writeValueAsString(article);
    }
}
